package cn.samler.project.guestbook.handler;

import cn.samler.project.guestbook.model.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;

@ControllerAdvice
@Slf4j
public class RequestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handler(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            FieldError fieldError = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError();
            if (fieldError != null) {
                return Response.builder().ret(Response.Ret.FAILURE).msg(fieldError.getDefaultMessage()).build();
            }
        }

        if (e instanceof BindException) {
            FieldError fieldError = ((BindException) e).getBindingResult().getFieldError();
            if (fieldError != null) {
                return Response.builder().ret(Response.Ret.FAILURE).msg(fieldError.getDefaultMessage()).build();
            }
        }

        log.error(e.getMessage());
        return Response.builder().ret(Response.Ret.FAILURE).msg(e.getMessage()).build();
    }

}
